<template>
  <view class="container">
    <!-- 导航栏 -->
    <custom-nav-bar
      title="六爻排盘"
      subtitle="专业预测，快速排盘"
      bg-color="#4B79FF"
    />

    <!-- 主体内容 -->
    <scroll-view class="content"
      scroll-y
      :style="{ 
        height: `calc(100vh - ${statusBarHeight}px -20rpx)`,
        paddingTop: '160rpx'
      }">
      
      <view class="form-card_top_content">
        <!-- 占事标题 -->
        <view class="form-item">
          <text class="label">占事标题</text>
          <input 
            class="input"
            v-model="formData.title"
            placeholder="请输入您所测何事"
            placeholder-class="placeholder"
          />
        </view>

        <!-- 起卦时间 -->
        <view class="form-item">
          <text class="label">起卦时间</text>
          <view class="time-picker">
            <uni-datetime-picker
              v-model="formData.datetime"
              type="datetime"
              @change="onTimeChange"
              :border="false"
              hide-second
            />
            <text class="time-text"></text><!-- {{ formatDateTime }}-->
          </view>
        </view>

        <!-- 起卦方式 -->
        <view class="form-item">
          <text class="label">起卦方式</text>
          <view class="selector-container" @click="showMethodSelector">
            <text class="dropdown-label">{{ formData.method.label }}</text>
            <image class="arrow-icon" :src="arrowIcon" mode="aspectFit" />
          </view>
              <SelectorPopup
                ref="methodPopup"
                :options="methodList"
                :currentValue="formData.method.value"
                headerText="选择起卦方式"
                @select="onMethodChange"
              />
        </view>
      </view>

      <view class="form-card_bottom_content">
        <!-- 手动起卦区域 -->
		<view class = "form-card-bottom-title">
			<view class ="title">手动起卦</view>
			<button class = "clear-btn" @tap="clearYaoData">清空</button>
		</view>
        <view v-if="formData.method.value === 'manual'" class="manual-area">
          <view 
            v-for="(item, index) in yaoList" 
            :key="index"
            class="yao-item"
          >
            <text class="yao-label">{{ item.title }}</text>
            <view 
              class="yao-selector"
			  @click="showYaoSelector(index)"
            >
		    <view class="view-info">
			  <text class="yao-value">{{ formData.yaoData[index].preText || '请选择' }}</text>
			  <image class="gua-icon" :src="formData.yaoData[index].imagePath" mode="aspectFit"/>
			  <text class="yao-value">{{ formData.yaoData[index].endText }}</text>
		    </view>
			  
            <image class="arrow-icon" :src="arrowIcon" mode="aspectFit" /> 
			<SelectorPopup
						:ref="(el) => (yaoPopup[index] = el)"
				        :options="yaoOptions"
				        :currentValue="formData.yaoData[index].value"
				        headerText="选择爻值"
				        @select="selectYaoValue(index, $event)"
				    />    				 
            </view>
          </view>
        </view>

        <!-- 在线起卦区域 -->
        <view v-else class="online-area">
         
		   <view class="online-result" v-if="formData.method.value === 'online' &&  formData.yaoData.some(yao => yao.value !== '')">
		       <text class="result-label">在线起卦结果：</text>
		       <view class="result-list">
		         <view class="result-item" v-for="(yao, index) in formData.yaoData" :key="index">
		           <text class="result-text">{{ yao.preText }}</text>
				   <image class="popup-image" :src="yao.imagePath"  mode="widthFix" style="width: 60px; padding: 5px;"/>
				   <text class="result-text">{{ yao.endText }}</text>
		         </view>
		       </view>       
		    </view>
			<view v-else class="tips-container">
				 <text class="tips">点击下方按钮开始在线起卦</text>
				  <button 
				    class="online-btn"
				    @tap="startOnlineDivination">开始摇卦</button>
			</view>
		  
        </view>

        <!-- 提交按钮 -->
        <button 
          class="submit-btn"
          :disabled="!isFormValid"
          @tap="onSubmit"
        >
          查看卦象
        </button>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { ref, reactive, onMounted,onActivated,computed  } from 'vue'
import { Solar, Lunar } from 'lunar-javascript';
import CustomNavBar from '@/components/CustomNavBar.vue';
import SelectorPopup from '@/components/SelectorPopup.vue';
import { methodList, yaoList, yaoOptions } from '/static/data/defaultData.js';

export default {
  components: {
    CustomNavBar,
    SelectorPopup
  },
  setup() {
    // 系统信息
    const sysInfo = uni.getSystemInfoSync();
    const statusBarHeight = ref(sysInfo.statusBarHeight + 40);
    const navHeight = ref(statusBarHeight.value + 60); // 增加导航栏高度

    // 表单数据
    const formData = reactive({
      title: '',
      datetime: new Date(),
       method: { label: '手动起卦', value: 'manual' },
       yaoData: yaoList.map(() => ({ value: '', name: '' }))
    });

    // 当前选择的爻位索引
    // const currentYaoIndex = ref(-1);
    // const currentYaoValue = ref('');
	// const yaoPopup = ref([]);
	const yaoPopup = [];
    const methodPopup = ref(null);
    // 格式化日期时间
    const formatDateTime = computed(() => {
      const date = formData.datetime;
      const lunar = Lunar.fromDate(date);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')} 【${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}】`;
    });

    // 表单验证
    const isFormValid = computed(() => {
      // if (!formData.title.trim()) return false;
      if (!formData.datetime) return false;
      if (formData.method.value === 'manual' || formData.method.value ==='online') {
        return formData.yaoData.every(yao => yao.value !== '');
      }
      return false;
    });

    // 时间变更处理
    const onTimeChange = (date) => {
      formData.datetime = new Date(date);
    };

    // 显示起卦方式选择器
   const showMethodSelector = () => {
         if (methodPopup.value) {
           methodPopup.value.openPopup(); // 调用组件中的 openPopup 方法
         }
    };
   //起卦方式变更
    const onMethodChange = (option) => {
      formData.method = option;
	  clearYaoData();
    };   
	
	//显示爻
	const showYaoSelector = (index) => {
		console.log('asdfasdfas   '+index)
	 //      if (yaoPopup.value[index]) {
		// 	  console.log('asdfasdfas=======   '+index)
	 //        yaoPopup.value[index].openPopup();
	 //      }
	      if (yaoPopup[index]) {
	        yaoPopup[index].openPopup(); // 调用组件中的 openPopup 方法
	      } else {
	        console.error(`Popup for index ${index} is not available`);
	      }
	};
	
	//显示爻值选择器
	const selectYaoValue = (index, option) => {
	      formData.yaoData[index] = { value: option.value, preText: option.preText,imagePath:option.imagePath,endText:option.endText};
	};
	
	const clearYaoData = () => {
	      formData.yaoData = formData.yaoData.map(() => ({ value: '', preText: '',imagePath:'',endText:''}));
	};

    // 在线起卦
	const startOnlineDivination = () => {
        // 随机生成爻值
		formData.yaoData = Array.from({ length: 6 }, () => 
		{
			const randomYaoValue = Math.floor(Math.random() * 3) + 1;
			console.log('startOnlineDivination randomYaoValue:', randomYaoValue);
			const selectedOption = yaoOptions.find(option => option.value === randomYaoValue.toString());
			return { value: selectedOption.value, preText: selectedOption.preText,imagePath:selectedOption.imagePath,endText:selectedOption.endText };
		});
		console.log('startOnlineDivination formData.yaoData:', JSON.stringify(formData.yaoData));
    };

    // 提交表单
    const onSubmit = () => {
      if (!isFormValid.value) {
        uni.showToast({
          title: '请完善表单信息',
          icon: 'none'
        });
        return;
      }

      // 保存数据
      const yaoValues = formData.yaoData.map(item => item.value);
      const id = Math.floor(100000 + Math.random() * 900000).toString();
      const yaoData = {
        id: id,
        yaoDataValue: yaoValues.join(''),
        yaoDateTime: formData.datetime.toISOString(),
        yaoTitle: formData.title
      };

      // 保存到本地存储
      uni.setStorageSync(id, JSON.stringify(yaoData));

      // 保存所有ID到一个数组中
      let keys = uni.getStorageSync('keys') || [];
      if (!keys.includes(id)) {
        keys.push(id);
        uni.setStorageSync('keys', keys);
      }

      console.log('yaoData saved to local storage with ID:', id, yaoData);
  
	  uni.navigateTo({
		 url: `/pages/listindex/listindex?data=${JSON.stringify(yaoData)}`
	  });
    };

    return {
      statusBarHeight,
      navHeight,
      formData,
      methodList,
      yaoList,
      yaoOptions,
      formatDateTime,
      isFormValid,
      yaoPopup,
      methodPopup,
      arrowIcon: '/static/images/arrow_down.png',
      onTimeChange,
      onMethodChange,
      showMethodSelector,
      showYaoSelector,
      selectYaoValue,
      startOnlineDivination,
      onSubmit,
	  clearYaoData
    };
  }
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  .form-card_top_content{
	  background-color: #fff;
	  padding: 30rpx;
	  margin: 60rpx 20rpx 20rpx 20rpx;
	  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	  border-radius: 16rpx;
  }
  .form-card_bottom_content {
    background-color: #fff;
    padding: 30rpx;
    margin: 30rpx 20rpx 20rpx 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    border-radius: 16rpx;
	.form-card-bottom-title{
		flex-direction: row;
	}
	
  }
}

.form-item {
  margin-bottom: 30rpx;

  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
    display: block;
  }

  .input {
    width: 95%;
    height: 80rpx;
    background-color: #f7f7f7;
    border-radius: 8rpx;
    padding: 0 20rpx;
  }

  .placeholder {
    color: #999;
  }
}

.time-picker {
  background-color: #f7f7f7;
  border-radius: 8rpx;
  padding: 0 20rpx;
  height: 80rpx;
  display: flex;
  align-items: center;

  .time-text {
    font-size: 28rpx;
    color: #333;
  }
}

.selector-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f7f7f7;
  border-radius: 8rpx;
  padding: 0 20rpx;
  height: 80rpx;
  cursor: pointer;

  .dropdown-label {
    font-size: 40rpx;
    color: #333;
  }

  .arrow-icon {
    width: 24rpx;
    height: 24rpx;
	text-align: left;
  }
}
.form-card-bottom-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  width: 100%;
  // background-color: #3872FE;

  .title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
	width: 80%;
  }
  /* 清空按钮样式 */
  .clear-btn {
    font-size: 24rpx;
    color: #999;
    background-color: #eaeaea; /* 默认灰色底 */
    border: none;
    padding: 0rpx 15rpx; /* 添加内边距 */
    border-radius: 10rpx; /* 添加圆角 */
    transition: background-color 0.3s; /* 添加过渡效果 */
  }
  
  /* 清空按钮点击效果 */
  .clear-btn:active {
    background-color: #aaa; /* 点击时的背景颜色 */
  }

 
}
.manual-area,
.online-area {
  .yao-item{
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  height: 85rpx;
  }
  .tips-container {
    // margin-bottom: 20rpx;
	 display: flex;
	  flex-direction: column;
	  align-items: center;
	  margin-bottom: 30rpx;
  }

  .yao-label {
    font-size: 28rpx;
    color: #333;
    margin-right: 20rpx;
  }

  .yao-selector {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #f0f0f0;
    border-radius: 8rpx;
    padding: 0 20rpx;
	width: 80%;
	height:70rpx;
	

	.view-info{
		display: flex;
		align-items: center;
		// background-color: #000000;
		height:80rpx;
		.yao-value {
		  font-size: 28rpx;
		  color: #333;
		}
		
		.gua-icon {
		  width: 160rpx;
		  height:50rpx;
		  padding: 0 20rpx;
		  align-items:left;
		}
	}
    .arrow-icon {
      width: 24rpx;
      height: 24rpx;
	  align-items:flex-end;
	  // align-items: right;
    }	
  }

  .online-btn {
    width: 300rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #3872FE;
    color: #fff;
    border-radius: 40rpx;
    font-size: 28rpx;
	margin-top: 40rpx;
	&:disabled {
	    opacity: 0.6;
	}
  }
}
/* 在线起卦结果样式 */
.online-result {
  margin-bottom: 30rpx;
}

/* 结果标签样式 */
.result-label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
}

/* 结果列表样式 */
.result-list {
  display: flex;
  flex-direction: column;
  margin-top: 30rpx;
}

/* 结果项样式 */
.result-item {
  width: 100%;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 30rpx;
  display: flex;
  align-items: center;
  color: #333;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  justify-content: center;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.submit-btn {
  margin-top: 40rpx;
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #3872FE;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;

  &:disabled {
    opacity: 0.6;
  }
}
</style>